package com.framework.bdf4j.config;

import com.framework.bdf4j.comm.web.AuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.framework.bdf4j.comm.web.MyAuthenticationProvider;
import com.framework.bdf4j.sysadm.service.impl.MyUserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * <b>文件名： </b>WebSecurityConfig.java<br/>
 * <b>类描述： </b>Spring Security配置类<br/>
 */

@Configuration          // 配置文件
@EnableWebSecurity      // 开启Spring Security
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启Security的注解，我们可以在需要控制权限的方法上面使用@PreAuthorize，@PreFilter这些注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
    protected void configure(HttpSecurity http) throws Exception {

		http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
		http.csrf().disable();

		// 获取登录页面的参数.
        http.addFilterBefore(new AuthenticationFilter("/j_login"), UsernamePasswordAuthenticationFilter.class);
		
        //路由策略和访问权限的简单配置		
        http.authorizeRequests()
                //.antMatchers("/").permitAll()     //允许所有用户访问"/"
                .antMatchers("/net").permitAll()
                .anyRequest().authenticated()     //其他地址的访问均需验证权限
                .and()
            .formLogin()                
                .loginPage("/index")                
                .defaultSuccessUrl("/page/main",true)     //登录成功后跳转页面
                .loginProcessingUrl("/j_login")                
                .failureUrl("/index")       //登陆失败返回
                .permitAll()                
                .and()
            .logout()
            	//.logoutUrl("/user/logout")
                .logoutSuccessUrl("/index")            //退出登录后的默认url
                .permitAll();
        
        //session失效后跳转
        http.sessionManagement().invalidSessionUrl("/invalidSession");
        //只允许一个用户登录,如果同一个账户两次登录,那么第一个账户将被踢下线,跳转到登录页面
        http.sessionManagement().maximumSessions(1).expiredUrl("/index");
    }
	
	@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.authenticationProvider(myAuthenticationProvider());
    }
	
	@Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题		
        web.ignoring().antMatchers(
                "/admin/ideperm/**","/bus/**","/admin/user/test/**","/invalidSession","/sessiondata/*",
                "/register","/forgetPwd","/admin/user/checkCode","/admin/user/checkFpValidCode",
                "/admin/user/checkAccount","/admin/user/checkHasAccount","/admin/user/checkPhoneUnique",
                "/admin/user/getFpValidCode","/admin/user/modifyPwd","/admin/user/register",
                "/favicon.ico**","/logo.png","/css/**","/pages/**","/captcha**","/ajax/**","/page/error",
                "/fonts/**","/img/**","/js/**","/custom/**","/admin/tenant/list");
    }
	
	 /**
     * 设置用户密码的加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
    	return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /**
     * 自定义UserDetailsService，从数据库中读取用户信息
     */
    @Bean
    public MyUserDetailsService myUserDetailsService(){
        return new MyUserDetailsService();
    }
    
    /**
     * 自定义MyAuthenticationProvider
     */
    @Bean
    public MyAuthenticationProvider myAuthenticationProvider(){
        return new MyAuthenticationProvider();
    }
}
